package com.ly.chatsimple.ui.chat.viewmodel

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ly.chatsimple.ui.chat.state.ChatRecord
import com.ly.chatsimple.ui.chat.usecase.ChatSendUseCase
import com.ly.nethub.utils.LogUtils
import kotlinx.coroutines.launch


class ChatViewModel(
    private val sendUseCase: ChatSendUseCase = ChatSendUseCase()
) : ViewModel() {

    val recordList = mutableStateListOf<ChatRecord>()

    val recordListState = LazyListState(0, 0)

    fun onSend(value: String) {
        if (value.isEmpty()) return
        viewModelScope.launch {
            val senderRecord = ChatRecord(
                isSender = true,
                content = value,
            )
            recordList.add(senderRecord)
            scrollToBottom()
            val response = sendUseCase.sendMsg(value)
            LogUtils.d("$TAG 消息发送 ${response.isSuccess}")
        }
    }

    private suspend fun scrollToBottom() {
        val layoutInfo = recordListState.layoutInfo
        val totalItemCount = layoutInfo.totalItemsCount
        if (totalItemCount == 0) return
        recordListState.scrollToItem(layoutInfo.totalItemsCount - 1)
    }

    companion object {
        const val TAG = "ChatViewModel"
    }
}